var chat = {
	//连接建立时发送登录信息
	onopen : function(){
	    var _data = '{"type":"chatroomslist"}';
	    ws.send(_data);
	},
	onmessage : function(e){
		var data = eval("("+e.data+")");
	    switch(data['type']){
	        case 'chatroomslist':
	        	localStorage.setItem('chatroomslist',JSON.stringify(data.rooms));
	            initChatRooms(data);
	            break;
	    }
	},
};
mui.init();
mui.plusReady(function(e){
	window.addEventListener('loginSuccess',function(e){
		console.log('chatrooms.js收到loginSuccess');
		console.log(JSON.stringify(e));
	},false);
	window.addEventListener('updateData',function(e){
		var data = e.detail;
		console.log(JSON.stringify(data));
		switch(data['type']){
			case 'online':
				document.querySelector("#onlineNumbers").innerText = data['online'];
				//console.log(localStorage.getItem('rooms'));
				if(document.getElementById('roomslist').innerHTML==''){
					initChatRooms(data);
				}
				break;
			case 'init':
				initChatRooms(data);
				break;
		}
	},false);
	mui(".mui-scroll-wrapper").scroll();
	room_connect(chat.onopen,chat.onmessage);
	bindtap();
});

function bindtap(){
	mui("#roomslist").on("tap","a",function(e){
		var room_id = this.getAttribute("id");
		var room_type = this.getAttribute("roomtype");
		var room_name = this.getAttribute("roomname");
		userinfo = {
			'username' : localStorage.getItem("username"),
			'token' : localStorage.getItem('token'),
			'usertype' : localStorage.getItem('usertype'),
		}
		localStorage.setItem("room_id",room_id);
		
		if(parseInt(userinfo.usertype)==0 && parseInt(room_type)==1){
			mui.toast("本房间游客限制进入,请重新登录!");
			openLoginWindow(room_id);
			return false;
		}
		console.log(name);
		if(!userinfo['username']){
			openLoginWindow(room_id);
			return false;
		}
		openChatWindow(this.href,room_id,name,room_name);
	});
}

var initChatRooms = function(data){
	document.querySelector("#onlineNumbers").innerText = data['online'];
	var rooms = localStorage.getItem('chatroomslist');
	rooms = JSON.parse(rooms);
	//列出房间列表
    var rooms_ul = document.getElementById("roomslist");
	rooms_ul.innerHTML = template('roomTemplate', data);
    mui.fire(plus.webview.getWebviewById(plus.runtime.appid), 'webviewLoaded', {});
};
